package com.example.codereview;

import com.example.codereview.review.ReviewContent;
import com.example.codereview.util.IdeaUtils;
import com.example.codereview.util.JOptionPaneUtils;
import com.example.codereview.util.ObjectUtils;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;

import java.util.List;

public class CodeReviewAddAction extends AnAction {


    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        try {
            String selectCodeContent = IdeaUtils.getSelectCodeContent(e);
            new ReviewDialog(e,2,selectCodeContent);
        } catch (Exception e1) {
            e1.printStackTrace();
            JOptionPaneUtils.warn(e1.getMessage());
        }
    }



    @Override
    public void update(@NotNull AnActionEvent e) {
        //代码评审路径
        String codeReviewPath = IdeaUtils.codeReviewPath(e);
        //当前点击所在行号
        Editor editor = e.getData(PlatformDataKeys.EDITOR);
        if (e.getProject() != null && editor != null) {
            // 获取光标所在行号
            int lineNum = editor.getCaretModel().getLogicalPosition().line + 1; // 行号从1开始计数
            //代码评审内容
            List<ReviewContent> reviewContents  = IdeaUtils.parseObject(codeReviewPath);
            if(!ObjectUtils.isEmpty(reviewContents)) {
                VirtualFile file = e.getData(CommonDataKeys.VIRTUAL_FILE);
                ReviewContent reviewContent = reviewContents.stream().filter(r -> r.getNumber() == lineNum &&
                                file != null && r.getPath().equals(file.getPath()))
                        .findFirst().orElse(null);
                if (reviewContent != null) {
                    e.getPresentation().setEnabled(false);
                    return;
                }
            }
        }
        e.getPresentation().setEnabled(true);
    }
}
